package cn.smbms.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.RoleService;
import cn.smbms.service.UserService;
import cn.smbms.utils.Constants;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UserController {
	@Resource
	private UserService userService;
	
	@Resource
	private RoleService roleService;
	
	@RequestMapping("login")
	public String login() {
		return "login";
	}

	@RequestMapping("jsp/frame")
	public String frame() {
		return "jsp/frame";
	}
	
	@RequestMapping("login.do")
	public String logindo(String userCode, String userPassword,
			HttpSession session,
			Model model) {
		// 2、主体认证/授权请求
		Subject subject = SecurityUtils.getSubject();
		//
		UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
				"admin", "test");
		subject.login(usernamePasswordToken);
		System.out.println("isAuth:"+subject.getPrincipal() + " is " + subject.isAuthenticated());//是否认证
		//
		User user = userService.login(userCode, userPassword);
		if(user != null) {//登录成功
			System.out.println(userCode+"登录成功");
			//session.setAttribute("user", user);
			session.setAttribute(Constants.USER_SESSION, user);
			//dispatcher -> redirect
			return "redirect:jsp/frame";
		}
		model.addAttribute("error", "登录失败，用户名或密码错误");
		//默认到登录页面
		return "login";
	}
	
	@RequestMapping("logout.do")
	public String logout(HttpSession session) {
		//清除session
		session.removeAttribute(Constants.USER_SESSION);
		//跳转到登录页面
		return "redirect:login";
	}
	
	@RequestMapping("jsp/pwdmodify")
	public String pwdmodify() {
		return "jsp/pwdmodify";
	}
	
	@RequestMapping("jsp/user.do")
	public String userdo(String oldpassword, String newpassword,
			HttpSession session, Model model) {
		//1、从 session中取出当前登录用户信息
		User user = (User)session.getAttribute(Constants.USER_SESSION);
		//2、验证用户的原密码是否正确
		if(user.getUserPassword().equals(oldpassword)) {
			//3、修改密码
			//user.setUserPassword(newpassword);
			//int i = userService.modify(user);
			int i = userService.updatePwd(user.getId(), newpassword);
			if(i == 1) {
				model.addAttribute("message", "密码修改成功");
			} else {
				model.addAttribute("message", "密码修改出错，请与管理员联系");
			}
		} else {
			model.addAttribute("message", "您提供的原密码不正确");
		}
		
		return "jsp/pwdmodify";
	}
	
	@RequiresRoles("1")
	@RequestMapping("jsp/userlist.do")
	public String userlist(
			@RequestParam(name="pageIndex",required=false,defaultValue="1") Integer currentPageNo, 
			String queryname,
			@RequestParam(name="queryUserRole",required=false,defaultValue="0") Integer queryUserRole,
			String message,
			Model model){
		//多条件查询，例如增加角色条件
		User user = new User();
		//1、显示出角色列表 roleList = userService.getRoleList();
		List<Role> roleList = roleService.getRoleList();
		//2、取得 queryUserRole 参数值，声明参数 String queryUserRole
		//3、增加 userService 接口，userMapper.getUserListByMap，参考JUnit
		//4、分页的时候，需要把上一次选中的角色，保持原有选中状态（代码已经存在）
		//分页插件(当前是第几页，每页显示的记录行数)
		Page<Object> page = PageHelper.startPage(currentPageNo, 1);
		//查询所有用户
		List<User> userList = new ArrayList<User>();
		if(queryname != null && !"".equals(queryname)) {
			user.setUserName(queryname);
		}
		if(queryUserRole != null && queryUserRole != null)
		{
			user.setUserRole(queryUserRole);
		}
		//userList = userService.getUserListByUserName(queryname);
		userList = userService.getUserLists(user);
		//把分页相关数据传递到freemarker
		//当前页的实际数据List<User>
		model.addAttribute("userList", userList);
		model.addAttribute("roleList", roleList);
		//总记录数
		model.addAttribute("totalCount", page.getTotal());
		//当前是第几页
		model.addAttribute("currentPageNo", page.getPageNum());
		//一共有多少页
		model.addAttribute("totalPageCount", page.getPages());
		//传递查询参数
		model.addAttribute("queryname", queryname);
		model.addAttribute("queryUserRole", queryUserRole);
		//
		model.addAttribute("message", message);
		return "jsp/userlist";
	}

	@RequestMapping("jsp/list")
	public String list(
			@RequestParam(name="pageIndex",required=false,defaultValue="1") Integer currentPageNo,
			String queryname,
			@RequestParam(name="queryUserRole",required=false,defaultValue="0") Integer queryUserRole,
			String message,
			Model model){
		//查询所有角色
		List<Role> roleList = roleService.getRoleList();
		PageHelper.startPage(currentPageNo, 1);
		//多条件查询，例如增加角色条件
		User user = new User();
		List<User> userList = new ArrayList<User>();
		if(queryname != null && !"".equals(queryname)) {
			user.setUserName(queryname);
		}
		if(queryUserRole != null && queryUserRole != null)
		{
			user.setUserRole(queryUserRole);
		}
		userList = userService.getUserLists(user);
		PageInfo<User> pageInfo = new PageInfo<User>(userList, 5);
		//当前页的实际数据List<User>
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("roleList", roleList);
		//传递查询参数
		model.addAttribute("queryname", queryname);
		model.addAttribute("queryUserRole", queryUserRole);
		//
		model.addAttribute("message", message);
		return "jsp/list";
	}

	@RequestMapping("jsp/useradd")
	public String useradd(Model model){
		List<Role> roleList = roleService.getRoleList();
		model.addAttribute("roleList", roleList);
		return "jsp/useradd";
	}
	
	@RequestMapping("jsp/userview")
	public String userview(Integer userid, Model model){
		User user = userService.getUserById(userid);
		model.addAttribute("user", user);
		return "jsp/userview";
	}	
	
	@RequestMapping("jsp/usermodify")
	public String usermodify(Integer userid, Model model){
		User user = userService.getUserById(userid);
		List<Role> roleList = roleService.getRoleList();
		model.addAttribute("roleList", roleList);
		model.addAttribute("user", user);
		return "jsp/usermodify";
	}	
	
	@RequestMapping("jsp/usermodify.do")
	public String usermodifydo(User user, Model model){
		int i = userService.modify(user);
		if(i==1) {
			model.addAttribute("message", "修改成功");
		} else {
			model.addAttribute("message", "修改失败");
		}
		return "jsp/usermodify";
	}
	
	@RequestMapping("jsp/userdel")
	public String userdel(Integer userid, Model model){
		System.out.println("userid=" + userid);
		int i = userService.deleteById(userid);
		if(i==1) {
			model.addAttribute("message", "删除成功");
		} else {
			model.addAttribute("message", "删除失败");
		}
		return "redirect:userlist.do";
	}

	@PostMapping(value = "/user/uploadHead", produces = {"application/json;charset=UTF-8"})
	@ResponseBody
	public Map<String, Object> userUpload(MultipartFile pic) {

		System.out.println(pic);

		Map<String, Object> result = new HashMap<>() ;
		result.put("code",200) ;
		return result ;
	}
}
